// DOM元素
const messageAlert = document.getElementById('messageAlert');
const setupPhone = document.getElementById('setupPhone');

// 显示消息提示
function showMessage(message, type = 'info') {
    messageAlert.textContent = message;
    messageAlert.className = `message-alert ${type}`;
    messageAlert.style.display = 'block';
    
    setTimeout(() => {
        messageAlert.style.display = 'none';
    }, 3000);
}

// 获取URL参数
function getUrlParam(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    const phone = getUrlParam('phone');
    if (phone) {
        setupPhone.value = phone;
    } else {
        showMessage('无效的访问', 'error');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1500);
    }
});

// 设置密码表单处理
document.getElementById('setupPasswordForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('setupUsername').value;
    const password = document.getElementById('setupPassword').value;
    const email = document.getElementById('setupEmail').value;
    const phone = setupPhone.value;
    
    try {
        const response = await fetch('/api/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password, phone, email })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showMessage('注册成功，正在自动登录...', 'success');
            // 自动登录
            const loginResponse = await fetch('/api/auth/login-by-sms', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ phone, code: 'auto' })
            });
            
            const loginData = await loginResponse.json();
            
            if (loginResponse.ok) {
                setTimeout(() => {
                    window.location.href = 'user-info.html';
                }, 1500);
            } else {
                showMessage('自动登录失败，请手动登录', 'warning');
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1500);
            }
        } else {
            showMessage(data.message, 'error');
        }
    } catch (error) {
        showMessage('注册失败，请稍后重试', 'error');
    }
}); 